﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Collections.Specialized;
using System.Web.UI.WebControls;

namespace Alerts_Administration_2010.classes.views.templates
{
    public abstract class AlertViewTemplateBase : IBindableTemplate
    {
        protected Control Control;

        protected abstract Control CreateControl();
        protected abstract string GetBoundPropertyNames();
        protected abstract object GetValue(string propertyName);
        protected abstract void BindControl(DetailsViewItemBLL boundItem);

        private bool instantiated = false;

        public void InstantiateIn(Control container)
        {
            if (instantiated) return;
            Control = CreateControl();
            Control.ID = container.ID + "_" + GetBoundPropertyNames();
            Control.DataBinding += new EventHandler(Control_DataBinding);
            container.Controls.Add(Control);
            instantiated = true;
        }
        public IOrderedDictionary ExtractValues(Control container)
        {
            InstantiateIn(container);
            OrderedDictionary result = new OrderedDictionary();
            foreach (string propertyName in GetBoundPropertyNames().Split(','))
            {
                string property = propertyName.Trim();
                result.Add(property, GetValue(property));
            }
            return result;
        }

        private void Control_DataBinding(object sender, EventArgs e)
        {
            DetailsView container = (DetailsView)Control.NamingContainer;
            DetailsViewItemBLL item = container.DataItem as DetailsViewItemBLL;
            if (item == null) return;
            BindControl(item);
        }
    }
}
